from flask import url_for
from sqlalchemy.exc import SQLAlchemyError

from ext import db


class Todo(db.Model):
    """
    任务清单表
    """
    __tablename__ = 'todo'
    id = db.Column(db.Integer, autoincrement=True, primary_key=True, nullable=False)
    title = db.Column(db.String(60), nullable=False)
    description = db.Column(db.String(60), nullable=False)
    done = db.Column(db.Boolean, nullable=False)

    def get(self, id):
        return self.query.filter_by(id=id).first()

    def add(self, user):
        db.session.add(user)
        return session_commit()

    def update(self):
        return session_commit()

    def delete(self, id):
        self.query.filter_by(id=id).delete()
        return session_commit()

    def to_json(self):
        json_post = {
            # 蓝图名称+视图函数名称
            'url': url_for('todo_v1.get_tasks_list', id=self.id, _external=True),
            'title': self.title,
            'description': self.description,
            'done': self.done
        }
        return json_post


def session_commit():
    try:
        db.session.commit()
    except SQLAlchemyError as e:
        db.session.rollback()
        reason = str(e)
        return reason
